package com.niit.happynicedays;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

public class option extends Activity implements OnClickListener {

	Button btGiam, btTang, btOK;
	TextView edText;
	Handler edtHandler;
	int volume;
	String filename = "config.cfg";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.option);

		btGiam = (Button) findViewById(R.id.btGiam);
		btGiam.setOnClickListener(this);
		btTang = (Button) findViewById(R.id.btTang);
		btTang.setOnClickListener(this);
		btOK = (Button) findViewById(R.id.btOK);
		btOK.setOnClickListener(this);
		edText = (TextView) findViewById(R.id.edText);

		try {
			FileInputStream fis = openFileInput(filename);
			volume = fis.read();
			fis.close();
		} catch (Exception e) {
			// TODO: handle exception
		}

		edText.setText(Integer.toString(volume));

		edtHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				edText.setText(Integer.toString(volume));
				super.handleMessage(msg);
			}
		};

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			thoat();
		}
		return super.onKeyDown(keyCode, event);
	}
	
	public void thoat() {
		Intent intent = new Intent(getBaseContext(), mainmenu.class);
		startActivity(intent);
		finish();
	}

	public void giam() {
		if (volume > 0) {
			volume -= 1;
			edtHandler.sendEmptyMessage(0);
		}
	}

	public void tang() {
		if (volume < 10) {
			volume += 1;
			edtHandler.sendEmptyMessage(0);
		}
	}

	public void thietlap() {
		try {
			FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
			fos.write(volume);
			fos.close();
			thoat();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btGiam:
			giam();
			break;
		case R.id.btTang:
			tang();
			break;
		case R.id.btOK:
			thietlap();
			break;
		default:
			break;
		}
	}
}